﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Viyi.Util.Linq
{
    public static partial class EnumerableExtentions
    {
        public static T CompareToChoose<T>(this IEnumerable<T> source, Func<T, T, bool> chooseFirst)
        {
            return source.Aggregate((last, next) =>
            {
                return chooseFirst(next, last) ? next : last;
            });
        }

        public static T Max<T>(this IEnumerable<T> source, IComparer<T> comparer)
        {
            return source.Aggregate((last, next) =>
            {
                return comparer.Compare(next, last) > 0 ? next : last;
            });
        }

        public static T Min<T>(this IEnumerable<T> source, IComparer<T> comparer)
        {
            return source.Aggregate((last, next) =>
            {
                return comparer.Compare(next, last) < 0 ? next : last;
            });
        }

        public static TSource ByMax<TSource, TTarget>(this IEnumerable<TSource> source,
            Func<TSource, TTarget> selector)
        {
            var comaprer = Comparer<TTarget>.Default;

            return source.Aggregate((last, next) =>
            {
                return comaprer.Compare(selector(next), selector(last)) > 0
                    ? next
                    : last;
            });
        }

        public static TSource ByMin<TSource, TTarget>(this IEnumerable<TSource> source,
            Func<TSource, TTarget> selector)
        {
            var comaprer = Comparer<TTarget>.Default;

            return source.Aggregate((last, next) =>
            {
                return comaprer.Compare(selector(next), selector(last)) < 0
                    ? next
                    : last;
            });
        }
    }
}
